package com.quanquan.store.controller;

import base.BaseController;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.dto.KillDTO;
import com.quanquan.store.dto.ShoppingKillDTO;
import com.quanquan.store.entity.ShoppingKill;
import com.quanquan.store.request.ShoppingKillRequestBody;
import com.quanquan.store.service.ShoppingKillService;
import enums.ResCodeEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import utils.IpUtils;
import utils.StringUtil;
import web.response.ResultBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述:
 *
 * @ClassName: ShoppingKillController
 * @Author: xiaoqianh丶
 * @Date: 2019-06-29 15:43
 * @Version: V1.0
 */
@Controller
@RequestMapping("/shopping_kill")
public class ShoppingKillController extends BaseController {

    public static final String INTEGRAL = "integral";
    public static final String MONEY = "money";
    private final RestTemplate restTemplate;
    private final StringRedisTemplate stringRedisTemplate;
    private final ShoppingKillService shoppingKillService;
    public static final String USER_NUM = "userNum_";
    public static final String STRING = "_";


    public ShoppingKillController(ShoppingKillService shoppingKillService, StringRedisTemplate stringRedisTemplate, RestTemplate restTemplate) {
        this.shoppingKillService = shoppingKillService;
        this.stringRedisTemplate = stringRedisTemplate;
        this.restTemplate = restTemplate;
    }


    /**
     * 管理端创建商城秒杀商品
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public ResultBody createShopingKill(@RequestBody ShoppingKillRequestBody requestBody) {
        String shoppingKill = shoppingKillService.createShoppingKill(requestBody);
        if(shoppingKill==null){
            return new ResultBody(ResCodeEnum.FAIL.getCode(), "秒杀商品创建失败");
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), com.alibaba.fastjson.JSONObject.toJSON(shoppingKill));

    }


    /**
     * 管理端查询所有秒杀商品
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/query")
    @ResponseBody
    public Map<String, Object> findAllShoppingKill(ShoppingKillRequestBody requestBody) {

        Integer page = requestBody.getPage();
        if (null != page && page > 0) {
            page = page -1;
            requestBody.setPage(page);
        }
        KillDTO killDTO = shoppingKillService.queryAllShoppingKill(requestBody);
        Map<String, Object> data = new HashMap<>();
        if (null != killDTO) {
            data.put("size",killDTO.getSize());
            data.put("rows",killDTO.getShoppingKills());
            data.put("status",200);
            data.put("msg","success!");
            data.put("total",killDTO.getTotal());
        } else {
            data.put("size",10);
            data.put("rows",null);
            data.put("status",-200);
            data.put("msg","no data!");
            data.put("total",0);
        }
        return data;
    }


    /**
     * 前端查询所有秒杀商品
     * @return
     */
    @PostMapping("/query_web")
    @ResponseBody
    public ResultBody findAllShoppingKillWeb(@RequestBody ShoppingKillRequestBody requestBody){

        Integer page = requestBody.getPage() == null ? 0 : requestBody.getPage();
        Integer size = requestBody.getSize() == null ? 100 : requestBody.getSize();

        List<ShoppingKill> shoppingKills = shoppingKillService.queryAllShoppingKillWeb(page, size);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), com.alibaba.fastjson.JSONObject.toJSON(shoppingKills));

    }

    /**
     * 用户点击抢购按钮
     * @param requestBody
     * @return
     */
    @PostMapping("/click")
    @ResponseBody
    public ResultBody participateShoppingKill(@RequestBody ShoppingKillRequestBody requestBody) {


        String shoppingKillId = requestBody.getShoppingKillId();

        //判断是否可以点击
        //用户的id
        //秒杀商品的id
        //点击进入的时间(自己生成)
        //只要进到这里返回redis 里的值减掉1
        String userId = requestBody.getUserId();
        String openId = requestBody.getOpenId();
        String spbill_create_ip = IpUtils.getIpAddr(request);


        ShoppingKill shoppingKill = shoppingKillService.getShoppingKill(shoppingKillId);
        Integer statusNumLimit = shoppingKill.getStatusNumLimit();
        Boolean result =false;



        //判断是否会只能抢购已次
        if(statusNumLimit == 1){
            //判断用户是否支付完毕读取redis
            String uuid = stringRedisTemplate.opsForValue().get(USER_NUM + shoppingKillId + STRING + userId);
            if(StringUtil.isNotEmpty(uuid)){
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("uuid", uuid);
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), stringObjectHashMap);

            }
            Integer shopKillTimes = shoppingKill.getShopKillTimes();
            Integer statusDaily = shoppingKill.getStatusDaily();
            result = shoppingKillService.checkTimes(shopKillTimes, userId, shoppingKillId, statusNumLimit, statusDaily);
            if(!result){
                return new ResultBody(ResCodeEnum.SHOPPINGKILL_COUNT.getCode(), ResCodeEnum.SHOPPINGKILL_COUNT.getMsg(), "用户秒杀次数不足");
            }




        }else{
            result= true;
            //判断之前是否有代付款
        }

        if(result){
            Long decr = shoppingKillService.decr(shoppingKillId);
            System.out.println("decr:......."+decr);
            String payType = shoppingKill.getPayType();
            if (decr <0L) {
                shoppingKillService.incr(shoppingKillId);
                return new ResultBody(ResCodeEnum.SHOPPINGKILL_FINISH.getCode(), ResCodeEnum.SHOPPINGKILL_FINISH.getMsg(), "商品已抢完");
            }
            if(payType.equals(MONEY)){
                //根据id查询缓存当缓存数变为0时返回已抢完
                //返回支付页面
                Map<String, Object> stringObjectMap = shoppingKillService.createshoppingRecord(userId, shoppingKill, openId, spbill_create_ip);

                if (stringObjectMap == null) {
                    shoppingKillService.incr(shoppingKillId);
                    return new ResultBody(ResCodeEnum.SHOPPINGKILL_ERROR.getCode(), ResCodeEnum.SHOPPINGKILL_ERROR.getMsg());

                }
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), stringObjectMap);
            }

            //校验用户积分是否能够支付
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(userId);
            idDTO.setIntegral(shoppingKill.getIntegral());
            Boolean aBoolean = restTemplate.postForObject("http://QUANQUAN-USER/user/check_balance", idDTO, Boolean.class);
            if (aBoolean) {

                //根据id查询缓存当缓存数变为0时返回已抢完
                //返回支付页面
                Map<String, Object> stringObjectMap = shoppingKillService.createshoppingRecord(userId, shoppingKill, openId, spbill_create_ip);

                if (stringObjectMap == null) {
                    shoppingKillService.incr(shoppingKillId);
                    return new ResultBody(ResCodeEnum.SHOPPINGKILL_ERROR.getCode(), ResCodeEnum.SHOPPINGKILL_ERROR.getMsg());

                }
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), stringObjectMap);
            } else {
                shoppingKillService.incr(shoppingKillId);
                return new ResultBody(ResCodeEnum.INTEGRAL_DEFICIENCY.getCode(), ResCodeEnum.INTEGRAL_DEFICIENCY.getMsg(), "用户积分不足");
            }
        }

        return new ResultBody(ResCodeEnum.SHOPPINGKILL_COUNT.getCode(), ResCodeEnum.SHOPPINGKILL_COUNT.getMsg(), "用户无法秒杀");

    }


    /**
     * 前端查询秒杀活动详情
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResultBody findShoppingKillDetails(@RequestBody ShoppingKillRequestBody requestBody) {
        String shoppingKillId = requestBody.getShoppingKillId();
        ShoppingKillDTO shoppingKillDTO = shoppingKillService.queryShoppingDetails(shoppingKillId);
        if (shoppingKillDTO == null) {
            return new ResultBody(ResCodeEnum.SHOPPINGKILL_OVER.getCode(), ResCodeEnum.SHOPPINGKILL_OVER.getMsg(), shoppingKillDTO);

        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), shoppingKillDTO);

    }


    /**
     * 后端端查询秒杀活动详情
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/edit_management")
    @ResponseBody
    public ResultBody findShoppingKillDetailsManagement(@RequestBody ShoppingKillRequestBody requestBody) {
        String shoppingKillId = requestBody.getShoppingKillId();
        ShoppingKillDTO shoppingKillDTO = shoppingKillService.queryShoppingDetailsManagement(shoppingKillId);
        if (shoppingKillDTO == null) {
            return new ResultBody(ResCodeEnum.SHOPPINGKILL_OVER.getCode(), ResCodeEnum.SHOPPINGKILL_OVER.getMsg(), shoppingKillDTO);

        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), shoppingKillDTO);

    }



    //上下加要处理缓存
    @PostMapping("/update")
    @ResponseBody
    public ResultBody updateShoppingKill (@RequestBody ShoppingKillRequestBody requestBody ){

        String msg = shoppingKillService.updateShoppingKill(requestBody);
        if(StringUtil.isEmpty(msg)){
            return new ResultBody(ResCodeEnum.FAIL.getCode(), "秒杀商品修改失败");

        }
        System.out.println("msg...."+msg);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), msg);

    }


    /**
     * 修改库存
     * @param id
     * @return
     */
    @PostMapping("/put_away")
    @ResponseBody
    public ResultBody putAway (String id){
        ShoppingKill shoppingKill = shoppingKillService.shoppingKillDetails(id);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), shoppingKill);
    }
}
